package com.newupbank.schedule.mail.task;

import cn.hutool.core.collection.CollectionUtil;
import com.newupbank.schedule.mail.dao.ICronDao;
import com.newupbank.schedule.mail.dao.IMailDao;
import com.newupbank.schedule.mail.vo.CronVO;
import com.newupbank.schedule.mail.vo.DifinedContentVO;
import com.newupbank.schedule.mail.vo.MailConfigVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author: liminghui
 * @date: 2021/1/17 23:09
 * @version: 1.0
 * @description: 适合从数据库读动态读取配置
 */
@Component
@EnableScheduling
public class MailScheduleTask2 implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(MailScheduleTask2.class);
    @Autowired
    private SendMailMsg sendMailMsg;

    @Autowired
    private IMailDao mailDao;

    @Autowired
    private ICronDao cronDao;

    private List<DifinedContentVO> difinedContentVOs;

    // @Value("${mail.task.cron}")
    // private String mailTaskCron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        CronVO cronVO = cronDao.queryCronVOByType("mail");

        // 处理自定义内容的集合，若配置了自定义的优先取自定义的，并将数据库置为0
        List<MailConfigVO> mailConfigVOList = mailDao.queryAllMailConfigVO();
        difinedContentVOs = mailDao.queryDifinedContent();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (CollectionUtil.isEmpty(difinedContentVOs)) { // 若自定义的全部更新为0就全部更新为1继续
                    int count = mailDao.updateAllValidToOne();
                    logger.info("MailScheduleTask2--->updateAllValidToOne is ok;count={}", count);
                    difinedContentVOs = mailDao.queryDifinedContent();
                }
                DifinedContentVO difinedContentVO = difinedContentVOs.get(0);
                String msg = difinedContentVO.getContentExtra();
                difinedContentVOs.remove(0);
                Integer id = difinedContentVO.getId(); //自定义消息的内容id
                logger.info("MailScheduleTask2--->executeTask is successful");

                for (MailConfigVO mailConfigVO : mailConfigVOList) {
                    String message = (msg != null) ?
                            msg :
                            sendMailMsg.getOneMessage(mailConfigVO.getContentFromUrl());
                    message += "\r\n愿意支持你一辈子的老男孩！";
                    sendMailMsg.sendMessage(mailConfigVO, message);
                }
                logger.info("MailScheduleTask2--->executeTask is successful");

                //更新已经发送的id值 --Valid改为0
                if (id != null) {
                    int count = mailDao.updateValidById(id);
                    logger.info("MailScheduleTask2--->updateValidById is ok;id={};count={}", id, count);
                }
            }
        };

        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                if (cronVO == null || StringUtils.isEmpty(cronVO.getCron())) {
                    return null;
                }
                //2.3 返回执行周期(Date)
                CronTrigger cronTrigger = new CronTrigger(cronVO.getCron());
                Date date = cronTrigger.nextExecutionTime(triggerContext);
                return date;
            }
        };

        taskRegistrar.addTriggerTask(runnable, trigger);
    }
}
